package com.wushi.lenovo.asia5b.app_ui.login.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;

import com.example.umeng_sdk.ThirdInfoModel;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.Profile;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.mvp.base.BaseMvpActivity;
import com.mvp.common.GlobalValue;
import com.mvp.utils.ToastUtil;
import com.wushi.lenovo.asia5b.BuildConfig;
import com.wushi.lenovo.asia5b.R;
import com.wushi.lenovo.asia5b.app_config.CommonConstant;
import com.wushi.lenovo.asia5b.app_di.APPComponentFactory;
import com.wushi.lenovo.asia5b.app_di.login.mvpview.LoginThridActivityView;
import com.wushi.lenovo.asia5b.app_di.login.presenter.LoginThridActivityPresenter;
import com.wushi.lenovo.asia5b.app_event.LoginEvent;
import com.wushi.lenovo.asia5b.app_model.profile.CountryModel;
import com.wushi.lenovo.asia5b.app_ui.other.dialog.FacebookMobileDialog;
import com.wushi.lenovo.asia5b.app_ui.other.dialog.ThirdLoginFailDialog;
import com.wushi.lenovo.asia5b.wxapi.WXLoginEvent;
import com.wushi.lenovo.asia5b.wxapi.WXUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import timber.log.Timber;

import static timber.log.Timber.d;

/**
 * Created by zhangyuncai on 2018/11/29.
 * 第三方登录
 */
public class LoginThridActivity extends BaseMvpActivity<LoginThridActivityView, LoginThridActivityPresenter> implements LoginThridActivityView {
    @BindView(R.id.facebook_loginthird)
    LoginButton facebook_loginthird;
    private List<CountryModel> countryModelList;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_loginthrid;
    }

    @Override
    protected void constructComponent() {
        APPComponentFactory.getAppBaseComponent().inject(this);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);

        initView();

        initData();

        initEvent();
    }

    @Override
    protected void initView() {
//        facebook_loginthird.setPermissions("email");
//        facebook_loginthird.setPermissions("email", "public_profile", "user_friends");
        //todo 只需要获取用户信息即可,不需要用户好友群组信息
        facebook_loginthird.setPermissions("email", "public_profile");
        callbackManager = CallbackManager.Factory.create();

        // Callback registration
        facebook_loginthird.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                AccessToken accessToken = loginResult.getAccessToken();
                getFacebookInfo(accessToken);

            }

            @Override
            public void onCancel() {
                if (BuildConfig.DEBUG) {
                    ToastUtil.showToast("onCancel");
                }
                // App code
            }

            @Override
            public void onError(FacebookException exception) {
                exception.printStackTrace();
                // App code
                if (BuildConfig.DEBUG) {
                    ToastUtil.showToast("onError" + exception.getMessage());
                }
            }
        });

    }

    public void getFacebookInfo(AccessToken accessToken) {
        String userId = accessToken.getUserId();
        GraphRequest request = GraphRequest.newMeRequest(
                accessToken,
                new GraphRequest.GraphJSONObjectCallback() {
                    @Override
                    public void onCompleted(
                            JSONObject object,
                            GraphResponse response) {
                        //{"id":"290599761504498","first_name":"岩","last_name":"刘"}
                        if (response.getError() != null) {
                        } else {
                            d("--->>>>>>>>---object:" + object.toString());
                            String email = object.optString("email");
                            String userid = object.optString("id");
                            String name = "";
                            try {


                                String first_name = object.optString("first_name");
                                String last_name = object.optString("last_name");
                                Profile currentProfile = Profile.getCurrentProfile();
                                name = currentProfile.getName();
                                Timber.d("--->>>>>>>>---"
                                        + "name  " + currentProfile.getName() + "  email  " + email + "  gender  " + object.optString("gender") + "  user_birthday  " + object.optString("birthday"));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            LoginManager.getInstance().logOut();//拿到个人消息后,退出facebook登录
                            if (TextUtils.isEmpty(email)) {//todo 没有邮箱也表示注册失败
                                new ThirdLoginFailDialog(mActivity).show();
                                return;
                            }
                            ThirdInfoModel infoModel = new ThirdInfoModel();
                            infoModel.setEmail(email);
                            infoModel.setName("");
                            infoModel.setUid(userid);
                            infoModel.setPlatform(ThirdInfoModel.SHARE_MEDIA.FACEBOOK);

                            login(infoModel);

                        }
                    }
                });
        Bundle parameters = new Bundle();
        parameters.putString("fields", "id,first_name,last_name,email,gender,birthday");
        request.setParameters(parameters);
        request.executeAsync();

    }

    @Override
    protected void initData() {
        getPresenter().getCountrys();
    }

    private void login(ThirdInfoModel infoModel) {
        if (TextUtils.isEmpty(infoModel.getUid())) {
            new ThirdLoginFailDialog(mActivity).show();
            return;
        }

        getPresenter().login(infoModel);
    }

    @Override
    public void loginResult(boolean isLoginSuccess) {
        if (isLoginSuccess) {
            finish();
        }
    }

    @Override
    public void getCountrysResult(List<CountryModel> countryModels) {
        countryModelList = countryModels;
    }

    @Override
    public void facebookLoginError(ThirdInfoModel infoModel) {
        Observable.just(1)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(integer -> {
                    FacebookMobileDialog dialog = new FacebookMobileDialog(this, countryModelList, infoModel);
                    dialog.show();
                });
    }

    @Override
    protected void initEvent() {

    }

    @OnClick({
            R.id.tv_loginthird_login,
            R.id.tv_loginthird_register,
            R.id.ll_loginthird_facebook,
            R.id.ll_loginthird_google,
            R.id.ll_loginthird_weixin,
            R.id.ll_loginthird_skip
    })
    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.tv_loginthird_login: {
                startActivity(new Intent(this, LoginUserActivity.class));
            }
            break;
            case R.id.tv_loginthird_register: {
                startActivity(new Intent(this, RegisterActivity.class));
            }
            break;
            case R.id.ll_loginthird_facebook: {
                AccessToken currentAccessToken = AccessToken.getCurrentAccessToken();
                if (currentAccessToken != null && !currentAccessToken.isExpired()) {
                    if (GlobalValue.isDebug) {
                        ToastUtil.showToast("facebook之前已登录,立即登录");
                    }
                    getFacebookInfo(currentAccessToken);
                    return;
                }
//                if (GlobalValue.isDebug) {
//                    String email = "166012364@qq.com";
//                    String userid = "166012364";
//                    String name = "166012364";
//                    ThirdInfoModel infoModel = new ThirdInfoModel();
//                    infoModel.setEmail(email);
//                    infoModel.setName(name);
//                    infoModel.setUid(userid);
//                    infoModel.setPlatform(SHARE_MEDIA.FACEBOOK);
//                    login(infoModel);
//                    return;
//                }

                facebook_loginthird.performClick();
//                UMShareAPI.get(this).getPlatformInfo(this, SHARE_MEDIA.FACEBOOK, authListener);
//                LoginManager.getInstance().logInWithReadPermissions(mActivity, Arrays.asList("email"));
            }
            break;
            case R.id.ll_loginthird_google: {
                if (true) {
                    ToastUtil.showToast("尽情期待...");
                    return;
                }
            }
            break;
            case R.id.ll_loginthird_weixin: {
                if (GlobalValue.isDebug) {
                    String email = "12347@qq.com";
                    String userid = "oC7jGwm53mX6X1ys3O0lrsxHbkMc";
                    String name = "张运才";
                    ThirdInfoModel infoModel = new ThirdInfoModel();
                    infoModel.setEmail(email);
                    infoModel.setUid(userid);
                    infoModel.setName(name);
                    infoModel.setPlatform(ThirdInfoModel.SHARE_MEDIA.WEIXIN);
                    login(infoModel);
                    return;
                }
                new WXUtils().login(mActivity);
            }
            break;
            case R.id.ll_loginthird_skip: {
                finish();
            }
            break;
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onLoginEvent(LoginEvent event) {
        if (event != null) {
            if (TextUtils.equals(event.loginState, CommonConstant.LOGIN_SUCCESS)) {
                d("--->>>>>>>>---登录成功");
                finish();
            }

        }
    }

    private CallbackManager callbackManager;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        callbackManager.onActivityResult(requestCode, resultCode, data);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onWXLoginEvent(WXLoginEvent event) {
        ThirdInfoModel infoModel = new ThirdInfoModel();
        infoModel.setEmail("");
        infoModel.setUid(event.wxLoginModel.getOpenid());
        infoModel.setName(event.wxLoginModel.getNickname());
        infoModel.setPlatform(ThirdInfoModel.SHARE_MEDIA.WEIXIN);
        login(infoModel);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


}
